// 需要将每个课程里面的学生进行分组，然后的不同小组之间进行相互匹配，然后互相批改作业
const router = require('koa-router')()

router.prefix('/information')

// 这个是为了该课程而进行分配小组, 以五个人为一小组，然后如果由于课程人数问题，会存在有的小组不足五个人的情况
router.post('/distributionGroup', async (ctx, next) => {
    console.log(ctx.request.body);
    let course_id = ctx.request.body.id;
    let sql = "select student_id from student_course_relation where course_id = ?";
    let res = await ctx.db.EXCUTE(sql, [course_id]);
    console.log(res, "查询结果");
    // 以五个人为一小组
    let groupSize = 5;
    let groups = randomGroupAssignment(res, groupSize);
    console.log(groups);

    let groupIDArr = [];
    for (let i = 0; i < groups.length; i++) {
        let datacenterId = i + 1; // 根据需要设置不同的数据中心ID
        let workerId = i + 1; // 根据需要设置不同的工作器ID
        let id = ctx.snowFlake.createSnow(datacenterId, workerId);
        while(groupIDArr.includes(id)) {
            id = ctx.snowFlake.createSnow(datacenterId, workerId);
        }
        groupIDArr.push(id);
        // console.log(id, "雪花ID");
    }
    
    let addGroup = "insert into groupinfo (group_id, course_id, group_number) values ";
    let addGroupRelation = "insert into group_student_relation (group_id, student_id) values ";
    let addGroupCorrection = "insert into group_correction (group_id, correction_group) values ";
    let addGroupArr = [];
    let addGroupCorrectionArr = [];
    for(let i = 0 ; i < groups.length; i++) {
        console.log(`小组 成员:`, groups[i].members);
        console.log(groups[i].peerIndex, "需要批改的小组");
        console.log(groupIDArr[groups[i].peerIndex], "需要批改的小组");
        let sql2 = `('${groupIDArr[i]}', '${groupIDArr[groups[i].peerIndex]}')`
        
        groups[i].members.push(groupIDArr[i]);
        // console.log(`对应的批改小组:`, peerGroup.members);
        let sql = `('${groupIDArr[i]}', '${course_id}', ${groups[i].members.length - 1})`
        addGroupArr.push(sql);
        console.log(sql2, "sql2");
        addGroupCorrectionArr.push(sql2);
    }
    
    if(addGroupArr.length > 0) {
        addGroup += addGroupArr.join(", ");
        let res = await ctx.db.EXCUTE(addGroup, []);
        console.log(res);
    }
    
    if(addGroupCorrectionArr.length > 0) {
        addGroupCorrection += addGroupCorrectionArr.join(", ");
        console.log(addGroupCorrection, "slqdwihioh");
        let res = await ctx.db.EXCUTE(addGroupCorrection, []);
        console.log(res, "返回的是correction表的结果");
    }

    let addGroupRelationArr = [];
    groups.forEach(item => {
        console.log(item, "item");
        for(let i = 0 ; i < item.members.length - 1; i++) {
            let sql = `(${item.members[item.members.length - 1]}, '${item.members[i].student_id}')`;
            addGroupRelationArr.push(sql);
        }
    })

    if(addGroupRelationArr.length > 0) {
        addGroupRelation += addGroupRelationArr.join(', ');
        console.log(addGroupRelation, "relation");
        let res = await ctx.db.EXCUTE(addGroupRelation, []);
        console.log(res);
    }

    ctx.body = { code: 200, groups };
})

function randomGroupAssignment(students, groupSize) {
    const numGroups = Math.ceil(students.length / groupSize);
    const shuffledStudents = shuffleArray(students);
    const groups = new Array(numGroups).fill().map(() => ({ members: [], peerIndex: -1 }));
  
    let groupIndex = 0;
    let peerIndex = 0; // 设置初始批改小组索引为 0
    for (let i = 0; i < shuffledStudents.length; i++) {
      groups[groupIndex].members.push(shuffledStudents[i]);
      if (groups[groupIndex].members.length === groupSize) {
        // 设置需要批改的小组索引，确保不是自身
        groups[groupIndex].peerIndex = (peerIndex + 1) % numGroups;
        groupIndex++;
        peerIndex++;
      }
    }

  
    // 检查是否存在未匹配的小组，并为其分配批改小组
    const unassignedGroups = groups.filter(group => group.peerIndex === -1);
    for (let i = 0; i < unassignedGroups.length; i++) {
      // 查找下一个可用的批改小组索引，确保不是自身
      let nextPeerIndex = (peerIndex + 1) % numGroups;
      while (nextPeerIndex === groupIndex) {
        nextPeerIndex = (nextPeerIndex + 1) % numGroups;
      }
      unassignedGroups[i].peerIndex = nextPeerIndex;
      peerIndex++;
    }
  
    return groups;
  }

function shuffleArray(array) {
    // Fisher-Yates 洗牌算法
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array;
}

// 示例使用
const students = ["学生A", "学生B", "学生C", "学生D", "学生E", "学生F", "学生H", "学生I"];
const numGroups = 3;

const assignedGroups = randomGroupAssignment(students, numGroups);



// 打印每个小组的成员
assignedGroups.forEach((group, index) => {
    console.log(`小组 ${index + 1} 成员:`, group);
});

module.exports = router